<?php

namespace app\api\controller;

use app\api\model\InfoTypeModel;
use app\api\model\InfoTypeRecord;
use app\api\model\UserFoodModel;
use app\api\model\UserInfoModel;
use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['infoList'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    /*
     * 自定义数据列表
     */
    public function infoList()
    {

        $list = InfoTypeModel::where(['is_show' => 1])->order('weigh desc')->select();

        $this->success('请求成功', $list);

    }

    /*
     * 提交自定义数据
     */
    public function takeMyInfo()
    {
        $ids = input('post.ids');

//        $ids = '1,2,7,4,5,6';

        $ids = explode(',', $ids);

        $info = InfoTypeModel::where('id', 'in', $ids)->select();

        $model = new UserInfoModel();

        $model->where(['user_id' => $this->auth->id])->update(['is_title' => 0]);

        foreach ($info as $val) {
            $check = UserInfoModel::get(['type_id' => $val['id'], 'user_id' => $this->auth->id]);

            //BMI
            if ($val['id'] == 4) {
//                $tizhong = InfoTypeRecord::where(['user_id'=>$this->auth->id,'type_id'=>1])->max('id');
//                $shengao = InfoTypeRecord::where(['user_id'=>$this->auth->id,'type_id'=>2])->max('id');

                $userInfo = $this->auth->getUser();

                if (empty($userInfo['height']) || empty($userInfo['weight'])) {
                    $type_value = '';
                } else {
//                    $tizhong = InfoTypeRecord::where('id',$tizhong)->value('type_value');
//                    $shengao = InfoTypeRecord::where('id',$shengao)->value('type_value');

                    $type_value = $userInfo['weight'] / ($userInfo['height'] * $userInfo['height']) * 10000;
                    $type_value = sprintf("%.2f", $type_value);
                }
            } else {
                $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id']])->max('id');
                if ($value > 0) {
                    $type_value = InfoTypeRecord::where('id', $value)->value('type_value');
                } else {
                    $type_value = '';
                }
            }

            if (!$check) {
                $data = [
                    'user_id' => $this->auth->id,
                    'type_id' => $val['id'],
                    'type_value' => $type_value,
                    'company' => $val['company'],
                    'is_title' => 1
                ];

                $model->allowField(true)->isUpdate(false)->data($data);
                $model->save();
            } else {
                $check->type_value = $type_value;
                $check->is_title = 1;
                $check->save();
            }

        }

        $this->success('操作成功');
    }

    /*
     * 首页自定义数据展示
     */
    public function indexUserInfo()
    {
        $ids = UserInfoModel::where(['is_title' => 1, 'user_id' => $this->auth->id])->column('type_id');

        if (count($ids) <= 0) {
            $ids = [1, 2, 3, 4, 5, 6];
        }

        $info = InfoTypeModel::where('id', 'in', $ids)->select();

        $model = new UserInfoModel();

        $todayTime = strtotime(date('Y-m-d'))+43200;
        $yesterdayTime = strtotime(date('Y-m-d'))-43200;
        $timeWhere['taketime'] = ['between', [$yesterdayTime, $todayTime]];

        foreach ($info as $val) {

            $check = UserInfoModel::get(['type_id' => $val['id'], 'user_id' => $this->auth->id]);

            //BMI
            if ($val['id'] == 4) {
//                $tizhong = InfoTypeRecord::where(['user_id'=>$this->auth->id,'type_id'=>1])->max('id');
//                $shengao = InfoTypeRecord::where(['user_id'=>$this->auth->id,'type_id'=>2])->max('id');

                $userInfo = $this->auth->getUser();

                if (empty($userInfo['height']) || empty($userInfo['weight'])) {
                    $type_value = '';
                } else {
//                    $tizhong = InfoTypeRecord::where('id',$tizhong)->value('type_value');
//                    $shengao = InfoTypeRecord::where('id',$shengao)->value('type_value');

                    $type_value = $userInfo['weight'] / ($userInfo['height'] * $userInfo['height']) * 10000;
                    $type_value = sprintf("%.2f", $type_value);
                }
            } else {
                //只读当天的数据
                $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id'], 'day' => date('Y-m-d')])->max('id');
                if ($value > 0) {
                    $type_value = InfoTypeRecord::where('id', $value)->value('type_value');

                    if ($val['id'] == 21) {
                        $type_value = explode(',', $type_value);
                        $type_value = $type_value[1] . '/' . $type_value[0];
//                        $type_value = str_replace(",","/",$type_value);
                    }
                } else {
                    $type_value = '';
                }

                if ($val['id'] == 9) {
                    $sum = UserFoodModel::where(['user_id' => $this->auth->id, 'day' => date('Y-m-d')])->sum('hot');
                    $type_value = sprintf("%.2f", $sum);
                    $val['company'] = 'kcal';
                }
                if ($val['id'] == 5) {
                    $sum = UserFoodModel::where(['user_id' => $this->auth->id, 'day' => date('Y-m-d')])->sum('protein');
                    $type_value = sprintf("%.2f", $sum);
                    $val['company'] = 'g';
                }
                if ($val['id'] == 14 || $val['id'] == 16 || $val['id'] == 18 || $val['id'] == 19) {
//                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id'], 'day' => date('Y-m-d')])->count();
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id']])->where($timeWhere)->count();
                    $type_value = $value * 10;
                    if ($type_value > 60) {
                        $xiaoshi = floor($type_value / 60);    //取小时
                        $fenzhong = $type_value - ($xiaoshi * 60);
//                        $type_value =  sprintf("%.2f",($type_value / 60));
                        $type_value = $xiaoshi . '.' . $fenzhong;
                        $val['company'] = 'h';
                    }
                }
                if ($val['id'] == 17) {
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id'], 'day' => date('Y-m-d')])->sum('type_value');
                    $type_value = $value;
                }
                if ($val['id'] == 24 || $val['id'] == 12) {
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id'], 'day' => date('Y-m-d')])->sum('type_value');
                    $type_value = sprintf("%.2f", $value);
                }

                if ($val['id'] == 6 || $val['id'] == 7) {
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id'], 'day' => date('Y-m-d')])->order('taketime desc')->value('type_value');
                    $type_value = sprintf("%.0f", $value);
                }
                if ($val['id'] == 23) {
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => $val['id'], 'day' => date('Y-m-d')])->avg('type_value');
                    $type_value = sprintf("%.1f", $value);
                }
                //清醒次数
                if($val['id'] == 25){
                    $qxData = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' =>16])->where($timeWhere)->order("type_value desc")->select();
                    $qxCounts = 0;
                    if(!empty($qxData)){
                        foreach ($qxData as $key => $value) {
                            if($key>0){
                                $breakTime = $qxData[$key-1]['type_value'] - $value['type_value'];
                                if($breakTime==600){//连续
                                    continue;
                                }
                            }
                            $qxCounts++;
                        }
                    }
                    $type_value = $qxCounts;

//                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' =>16, 'day' => date('Y-m-d')])->count();
//                    $type_value = $value;
                }
                //清醒时间
                if($val['id'] == 26){ 
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => ['in',[16,18,19]]])->where($timeWhere)->max('type_value');
                    // log_print(InfoTypeRecord::getLastsql(),$value);
                    if(!empty($value)){
                        $type_value = date('H:i',$value);
                    }else{
                        $type_value = '';
                    }
                }
                //睡觉时间
                if($val['id'] == 8){
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' =>14])->where($timeWhere)->value('taketime');
                    if(!empty($value)){
                        $type_value = date('H:i:s',$value-600);
                    }else{
                        $type_value = '';
                    }

                }

                if ($val['id'] == 20) {
                    $value = InfoTypeRecord::where(['user_id' => $this->auth->id, 'type_id' => ['in', [14, 16, 18, 19]]])->where($timeWhere)->count();
                    $type_value = $value * 10;
                    if ($type_value > 60) {
//                        $type_value =  sprintf("%.2f",($type_value / 60));
//                        $val['company'] = 'h';
                        $xiaoshi = floor($type_value / 60);    //取小时
                        $fenzhong = $type_value - ($xiaoshi * 60);
//                        $type_value =  sprintf("%.2f",($type_value / 60));
                        $type_value = $xiaoshi . '.' . $fenzhong;
                        $val['company'] = 'h';
                    }
                }
            }

            if (!$check) {
                $data = [
                    'user_id' => $this->auth->id,
                    'type_id' => $val['id'],
                    'type_value' => $type_value,
                    'company' => $val['company'],
                    'is_title' => 1
                ];

                $model->allowField(true)->isUpdate(false)->data($data);
                $model->save();
            } else {
                $check->type_value = $type_value;
                $check->company = $val['company'];
                $check->is_title = 1;
                $check->save();
            }

        }

        $list = UserInfoModel::where(['user_id' => $this->auth->id, 'is_title' => 1])->order('updatetime desc')->select();

        $this->success('请求成功', $list);
    }

    /*
     * 计算月经日历时间
     */
    public function mensesDays()
    {
        $user = $this->auth->getUser();
        $month = input('post.month');
//        $month = '2021-8';

        if (!$month) {
            $this->error('请先传入当前月份');
        }
        $month_arr = explode('-', $month);
        //经期长度
        $ses_length = $user['ses_length'];
//        $ses_length = 6;
        //周期长度
        $zhou_length = $user['zhou_length'];
        if (empty($zhou_length) || empty($ses_length)) {
            $this->error('请先补全经期信息');
        }
//        $zhou_length = 15;
        //月经第一天
        $first_day = $user['ses_first_day'];
//        $first_day = '2021-08-1';

        if (empty($first_day)) {
            $this->error('请先选择经期第一天');
        }

//        var_dump($month);
//        var_dump($first_day);
//        //两个日期之间差的月数
//        $cha_month = $this->getMonthNum($first_day, $month);

        //两个日期之间差的天数
        $cha_days = $this->diffBetweenTwoDays($first_day, $month);

//        var_dump('相差天数'.$cha_days);
//        //整除月数
//        $chu_month = intval($cha_days / $zhou_length);
        //剩余天数
        $num = $cha_days % $zhou_length;

//        var_dump('剩余天数'.$num);
//        $days = cal_days_in_month(CAL_GREGORIAN, $month_arr[1], $month_arr[0]);
//
//        //计算上次结束时间
//        $before_days = date('Y-m-d',strtotime('-'.$num.' day',strtotime($month)));

        $end_days = $zhou_length - $num;

        $now_days = date('d', strtotime('+' . $end_days . ' day', strtotime($month) - 1));
        $day_arr = [];
        $first_day_month = date('Y-m', strtotime($first_day));
//        if(strtotime($first_day) > strtotime($month)){
//            $this->success('请求成功',$day_arr);
//        }
//        var_dump($first_day_month);
        if ($first_day_month == $month) {
            $check_day = 0;
            for ($i = 0; $i < $ses_length; $i++) {
                $overdays = date('m', strtotime('+' . ($cha_days + $i) . ' day', strtotime($month)));
//                var_dump($overdays);
                if ($overdays != $month_arr[1]) {
                    continue;
                }
                $check_day = date('d', strtotime('+' . ($cha_days + $i) . ' day', strtotime($month)));


                $day_arr[] = date('Y-m-d', strtotime('+' . ($cha_days + $i) . ' day', strtotime($month)));
            }

            if ($check_day + $zhou_length < 31) {

                for ($i = 0; $i < $ses_length; $i++) {
                    $overdays2 = date('m', strtotime('+' . ($check_day + $zhou_length + $i) . ' day', strtotime($month)));
//                    var_dump($overdays2);
                    if ($overdays2 != $month_arr[1]) {
                        continue;
                    }

                    $day_arr[] = date('Y-m-d', strtotime('+' . ($check_day + $zhou_length + $i) . ' day', strtotime($month)));
                }
            }

        } else {

            if ($now_days < $zhou_length) {
                for ($i = 0; $i < $ses_length; $i++) {
                    $overdays = date('m', strtotime('+' . ($now_days - $zhou_length + $i) . ' day', strtotime($month)));
//                    var_dump($overdays);
                    if ($overdays != $month_arr[1]) {
                        continue;
                    }

                    $day_arr[] = date('Y-m-d', strtotime('+' . ($now_days - $zhou_length + $i) . ' day', strtotime($month)));
                }
            }

            for ($i = 0; $i < $ses_length; $i++) {
                $day_arr[] = date('Y-m-d', strtotime('+' . ($now_days + $i) . ' day', strtotime($month)));
            }

            $overdays = date('m', strtotime('+' . ($now_days + $zhou_length) . ' day', strtotime($month)));

            if ($overdays == $month_arr[1]) {
                for ($i = 0; $i < $ses_length; $i++) {
                    $overdays = date('m', strtotime('+' . ($now_days + $zhou_length + $i) . ' day', strtotime($month)));

                    if ($overdays != $month_arr[1]) {
                        continue;
                    }

                    $day_arr[] = date('Y-m-d', strtotime('+' . ($now_days + $zhou_length + $i) . ' day', strtotime($month) - 1));
                }
            }
        }


        $this->success('请求成功', $day_arr);


    }

    /**
     * 返回相差的月份数量
     * @param $date1 string 开始日期
     * @param $date2 string 结束日期
     * @return float|int
     */
    function getMonthNum($date1, $date2)
    {
        $date1_stamp = strtotime($date1);
        $date2_stamp = strtotime($date2);
        list($date_1['y'], $date_1['m']) = explode("-", date('Y-m', $date1_stamp));
        list($date_2['y'], $date_2['m']) = explode("-", date('Y-m', $date2_stamp));
        return abs($date_1['y'] - $date_2['y']) * 12 + $date_2['m'] - $date_1['m'];
    }


    /**
     * 求两个日期之间相差的天数
     * (针对1970年1月1日之后，求之前可以采用泰勒公式)
     * @param string $day1
     * @param string $day2
     * @return number
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    /**
     * 获取指定月的第几天的日期
     * @$year 年，$month月，$day天，$format显示时间的格式,$last是否该月最后一天
     * @return $str
     */
    function getMonthDay($year, $month, $day, $format = 'Y-m-d', $last = 0)
    {
        if ($last) {
            $time = new \DateTime($day);
            $d = strtotime($time->format("Y-m-d"));
            $d = date("t", $d);
            $time->setDate($year, $month, $d);
        } else {
            $time = new \DateTime();
            $time->setDate($year, $month, $day);
        }
        return $time->format($format);
    }

    function clearData()
    {
        $users = Db("info_type_record")->group('user_id')->field("user_id")->select();
        $users = array_column($users, 'user_id');
        $sql0 = "select * from fa_info_type_record where type_id =6 and user_id in(" . implode(',', $users) . ") order by taketime asc";
        log_print($sql0);
        $data = Db::query($sql0);
        $user_data = [];
        foreach ($data as $v) {
            $user_data[$v['user_id']][] = $v;
        }

//        log_print($data);
        $del_data = [];
        $save_data = [];
        foreach ($user_data as $user) {
            $is_data_1 = 0;
            foreach ($user as $kk => $vv) {
                if ($vv['taketime'] % 3600 != 0) {
                    if ($vv['type_value'] >= 100 || $vv['type_value'] <= 60) {
                        $is_data_1 = 1;
//                            array_push($save_data, $vv['id']);
                    } else {
                        array_push($del_data, $vv['id']);
                    }
                } else {
                    if ($is_data_1) {
                        array_push($del_data, $vv['id']);
                        $is_data_1 = 0;
                    } else {
//                            array_push($save_data, $vv['id']);
                    }
                }
            }
        }
        log_print($del_data);
        if (count($del_data) > 0) Db("info_type_record")->where('id', 'in', $del_data)->delete();

        $del_data = [];
        $sql0 = "select * from fa_info_type_record where type_id =21 and user_id in(" . implode(',', $users) . ") order by taketime asc";
        $data = Db::query($sql0);
        $user_data = [];
        foreach ($data as $v) {
            $user_data[$v['user_id']][] = $v;
        }
        foreach ($user_data as $user) {
            $is_data_2 = 0;
            foreach ($user as $kk => $vv) {
                if ($vv['taketime'] % 3600 != 0) {
                    $arr = explode(',', $vv['type_value']);
                    if (($arr[0] <= 60 || $arr[0] >= 90) ||
                        $arr[1] <= 90 || $arr[1] >= 140
                    ) {
                        $is_data_2 = 1;
//                            array_push($save_data, $vv['id']);
                    } else {
                        array_push($del_data, $vv['id']);
                    }
                } else {
                    if ($is_data_2) {
                        array_push($del_data, $vv['id']);
                        $is_data_2 = 0;
                    } else {
//                            array_push($save_data, $vv['id']);
                    }
                }
            }
        }
        log_print($del_data);
        if (count($del_data) > 0) Db("info_type_record")->where('id', 'in', $del_data)->delete();

        echo "success\n";
    }
}
